/**
* @ClassName: ActionCandidate
* @Description: 
* @author YuYang
* @date 2013-6-5 上午12:55:18
*/
package com.demodis.action;

import java.io.File;

import org.apache.struts2.ServletActionContext;

import com.demodis.domain.Json;
import com.demodis.domain.TblCandidate;
import com.demodis.domain.TblUser;
import com.demodis.service.CandidateServiceI;
import com.demodis.service.impl.CandidateServiceImpl;
import com.opensymphony.xwork2.ModelDriven;

public class CandidateAction extends BaseAction implements ModelDriven<TblCandidate> {

	private static final long serialVersionUID = 1L;
	
	String realPath = ServletActionContext.getServletContext().getRealPath("/imgs/vote");
	
	TblCandidate candidate = new TblCandidate();
	
	private CandidateServiceI candidateService = new CandidateServiceImpl();
	
	public void add() {
		Json json = new Json();
		if (candidateService.save(candidate, realPath + File.separator)) {
			json.setSuccess(true);
			json.setMsg("添加成功!");
		} else {
			json.setSuccess(false);
			json.setMsg("添加失败!");
		}

		super.writeJson(json);
	}
	
	public void delete() {
		Json json = new Json();
		if (candidateService.delete(candidate)) {
			json.setSuccess(true);
			json.setMsg("删除成功!");
		} else {
			json.setSuccess(false);
			json.setMsg("删除失败!");
		}

		super.writeJson(json);
	}
	
	public void modify() {
		Json json = new Json();
		if (candidateService.modify(candidate, realPath + File.separator)) {
			json.setSuccess(true);
			json.setMsg("修改成功!");
		} else {
			json.setSuccess(false);
			json.setMsg("修改失败!");
		}

		super.writeJson(json);
	}
	
	public void query() {
		super.writeJson(candidateService.get(candidate));
	}
	
	public void getCandidate() {
		super.writeJson(candidateService.getCandidate(candidate.getCanId()));
	}
	
	@Override
	public TblCandidate getModel() {
		return candidate;
	}
	
	public void getByCatId() {
		TblUser user = super.getCurrentUser();
		super.writeJson(candidateService.getByCatId(candidate.getCatId(), user.getUserId()));
	}
	
	public void getDetailedInfo() {
		super.writeJson(candidateService.getDetailedInfo(candidate.getCanId()));
	}
	
	public void doVote() {
		int userId = this.getCurrentUser().getUserId();
		Json json = new Json();
		if(candidateService.isVote(userId)) {
			json.setSuccess(false);
			json.setMsg("你已经投过票了!");
		}else {
			if (candidateService.doVote(candidate,userId)) {
				json.setSuccess(true);
				json.setMsg("投票成功!");
			} else {
				json.setSuccess(false);
				json.setMsg("投票失败!");
			}
		}

		super.writeJson(json);
	}
	
	public void queryVoteState() {
		super.writeJson(candidateService.queryVoteState(candidate));
	}

}
